/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hiddendanger.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.hiddendanger.bean.FreeSnapConfirmBean;
import com.koron.hiddendanger.domain.FreeSnap;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.hiddendanger.service.api.FreeSnapService;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.risk.domain.LocalHazardSource;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "freeSnap", description = "随手拍接口类")
@RestController
@RequestMapping("/freeSnap")
public class FreeSnapController {

    @Autowired
    private FreeSnapService snapService;
    private final static Logger logger = LoggerFactory.getLogger(FreeSnapController.class);

    @Autowired
    private Util util;

    @ApiOperation("保存或者提交随手拍接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc端不传，app端必传",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "新增时不传，修改时必传",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gridCode", value = "网格结点code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gridName", value = "网格结点名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceCode", value = "设备/作业编码",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceName", value = "设备/作业名称",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "description", value = "随手拍描述", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationType", value = "操作类型，0 保留，1 提交", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delFileAddress", value = "删除的文件地址",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keepFileAddress", value = "保留的文件地址",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "files", value = "上传的文件",  dataType = "file", paramType = "query"),
    })
    @RequestMapping(value = "/saveOrCommit.htm", method = RequestMethod.POST, consumes = "multipart/*", headers = "content-type=multipart/form-data")
    @Log(title = "保存/提交随手拍操作", businessModule = "随手拍", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> saveOrCommit(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String userCode, @ApiIgnore FreeSnap snap,
                                             @RequestParam final Integer operationType, @RequestParam(required = false) final String delFileAddress, @RequestParam(required = false) final String keepFileAddress,
                                             @RequestParam(required = false) final MultipartFile[] files) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        snap.setUpdateTime(new Date());
        snap.setUpdateUser(user.getName());
        snap.setSubmiterCode(user.getCode());
        return snapService.saveOrCommit(user, snap, operationType, files, delFileAddress, keepFileAddress);
    }

    @ApiOperation("删除随手拍接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "随手拍id,多个之间用,分开", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/deleteBatch.htm", method = RequestMethod.POST)
    @Log(title = "删除随手拍操作", businessModule = "随手拍", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> deleteBatch(@RequestParam final String ids) {
        return snapService.deleteBatch(ids == null ? null : Arrays.asList(ids.split("[，,]")));
    }

    @ApiOperation("根据主键获取随手拍详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "随手拍id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.POST)
    public MessageBean<FreeSnap> details(@RequestParam final String id) {
        return snapService.queryOne(id);
    }

    @ApiOperation("获取随手拍列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc端不传，app端必传",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "description", value = "随手拍描述",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gridCode", value = "网格结点code",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "submitTimeStart", value = "提交开始时间",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "submitTimeEnd", value = "提交结束时间",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "departCode", value = "部门code",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "submitCode", value = "提交人code",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "submitDepartmentName", value = "提交人单位名称",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词",  dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<FreeSnap>> queryByCondition(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String userCode,
                                                            @RequestParam(required = false) final String description, @RequestParam(required = false) final String corpCode,
                                                            @RequestParam(required = false) final String gridCode, @RequestParam(required = false) final Integer state,
                                                            @RequestParam(required = false) final @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd") Date submitTimeStart,
                                                            @RequestParam(required = false) final @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd") Date submitTimeEnd,
                                                            @RequestParam(required = false) final String departCode, @RequestParam(required = false) final String submitCode, @RequestParam(required = false) final String submitDepartmentName,
                                                            @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize,@RequestParam(required = false) final String keyword) {
        MessageBean<DataBean<FreeSnap>> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        msg = snapService.queryByCondition(user, description, corpCode, gridCode, state, submitTimeStart,
                submitTimeEnd, departCode, submitCode, submitDepartmentName, start, pageSize,keyword);
        if (null != msg.getData()) {
            msg.getData().setPageNo((page == null || page == 0) ? 1 : page);
            msg.getData().setPageSize((pageSize == null || pageSize == 0) ? 10 : pageSize);
        }
        return msg;
    }

    @ApiOperation("随手拍确认操作接口")
    @RequestMapping(value = "confirmFreeSnap.htm", method = RequestMethod.POST)
    @Log(title = "随手拍确认操作", businessModule = "随手拍", businessManipulation = BusinessManipulation.CONFIRM)
    public MessageBean<Integer> confirmFreeSnap(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody FreeSnapConfirmBean bean) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        if (null == bean) {
            msg.setCode(BusinessCode.FREESNAP_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.FREESNAP_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        String snapId = bean.getSnapId();
        FreeSnap snap = snapService.queryOne(snapId).getData();
        if (null == snap) {
            msg.setCode(BusinessCode.FREESNAP_NOT_EXISIT.getCode());
            msg.setDescription(BusinessCode.FREESNAP_NOT_EXISIT.getDescription());
            return msg;
        }
        String feedback = bean.getFeedback();
        Integer operationType = bean.getOperationType();
        LocalHazardSource localHazardSource = bean.getSource();
        HiddenDangerDiscovery dangerDiscovery = bean.getDiscovery();
        String userCode = bean.getUserCode();
        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
        if (null == user) {
            if (null != staffBeanList && staffBeanList.size() > 0) {
                user = staffBeanList.get(0);
            }
        }
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return snapService.confirmFreeSnap(snap, user, operationType, feedback, localHazardSource, dangerDiscovery);
    }

    @ApiOperation("随手拍列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "description", value = "随手拍描述",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gridCode", value = "网格结点code",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "submitTimeStart", value = "提交开始时间",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "submitTimeEnd", value = "提交结束时间",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "departCode", value = "部门code",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "submitCode", value = "提交人code",  dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/export.htm", method = RequestMethod.GET)
    public HttpEntity<?> export(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String description, String corpCode, String gridCode,
                                Integer state, Date submitTimeStart, Date submitTimeEnd,
                                String departCode, String submitCode) {
        if (null == user) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<FreeSnap> list = snapService.export(user, description, corpCode, gridCode, state, submitTimeStart,
                submitTimeEnd, departCode, submitCode);
        list.forEach(freeSnap -> {
            if (null != freeSnap.getSubmitTime()) {
                freeSnap.setSubmitTimeStr(sdf.format(freeSnap.getSubmitTime()));
            }
        });
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File targetFile = new File("static/excel/freeSnap.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/freeSnap.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("随手拍列表", targetFile, "freeSnap.btl", map);
    }
}
